package com.gzhryc.shared_device.oem.micro.api.controllers.xcx.v1.bxscn;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.DateTools;
import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBatteryType;
import com.gzhryc.shared_device.bxscn.code.dao.enums.BXSCNShopOrderEnum;
import com.gzhryc.shared_device.bxscn.code.dao.enums.EBXSCNCostMode;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryTypeService;
import com.gzhryc.shared_device.bxscn.code.services.dto.BXSCNShopOrderSearch;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.micro.api.MicroConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.bxscn.BXSCNMemberOrderInfoResponse;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.bxscn.BXSCNShopOrderListRequest;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.bxscn.BXSCNShopOrderListResponse;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.member.MemberOrderInfoRequest;

public class BXSCNShopOrderController {

    static Logger log = Logger.getLogger(BXSCNShopOrderController.class);

    @Route(value = { "/xcx/v1/member/bxscn_shop/order/list.data" }, method = "POST")
    public BXSCNShopOrderListResponse orderList(HttpServletRequest request) {
        BXSCNShopOrderListResponse apiResp = new BXSCNShopOrderListResponse(ClientAPICodeConstants.NULL_DATA, "无订单");
        BXSCNShopOrderListRequest apiReq = WebUtils.getJsonRequest(request, BXSCNShopOrderListRequest.class);
        if (apiReq != null && apiReq.getBody().getPageNo() != null) {
            LoginMember member = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
            BXSCNShopOrderSearch search = new BXSCNShopOrderSearch();
            search.setMemberId(member.getId());
            if(apiReq.getBody().getState() != null) {
                if (1 == apiReq.getBody().getState()) {         //待租借
                    search.setState(BXSCNShopOrderEnum.State.WaitLease.index());
                    search.setPayState(BXSCNShopOrderEnum.PayState.DepositSuccess.index());
                } else if (2 == apiReq.getBody().getState()){   //租借中
                    search.setState(BXSCNShopOrderEnum.State.Lease.index());
                    search.setPayState(BXSCNShopOrderEnum.PayState.DepositSuccess.index());
                } else if (3 == apiReq.getBody().getState()){   //待归还
                    search.setState(BXSCNShopOrderEnum.State.WaitRevert.index());
                    search.setPayState(BXSCNShopOrderEnum.PayState.DepositSuccess.index());
                } else if (4 == apiReq.getBody().getState()){   //已完成
                    search.setMinPayState(BXSCNShopOrderEnum.PayState.DepositRefund.index());
                }
            }
            //TODO 查询范围-年
            Date currentDate = new Date();
            List<BXSCNShopOrder> orderList = BXSCNShopOrderService.self(currentDate).findBySearch(search,apiReq.getBody().getPageNo(),MicroConstants.PAGE_LIMIT);
            if(orderList != null && orderList.size() > 0){
                apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setOrderItemList(new ArrayList<>());
                for(BXSCNShopOrder order : orderList) {
                    BXSCNShopOrderListResponse.OrderItem item = new BXSCNShopOrderListResponse.OrderItem();
                    item.setTradeNo(order.getTradeNo());
                    item.setBatteryType(order.getBatteryType());
                    item.setBatteryTypeName(order.getBatteryTypeName());
                    item.setBatteryPower(order.getBatteryPower());
                    item.setDeviceSn(order.getPortableBatterySn());
                    item.setPlaceName(order.getPlaceName());
                    item.setDepositMoneyStr(order.getDepositMoneyStr());
                    item.setMoneyStr(order.getMoneyStr());
                    item.setLeaseDay(order.getLeaseDay());
                    if(BXSCNShopOrderEnum.State.WaitLease.index().equals(order.getState())
                        && BXSCNShopOrderEnum.PayState.DepositSuccess.index().equals(order.getPayState())){
                        item.setState(1);
                        item.setStateName("待租借");
                    }else if(BXSCNShopOrderEnum.State.Lease.index().equals(order.getState())
                            && BXSCNShopOrderEnum.PayState.DepositSuccess.index().equals(order.getPayState())){
                        item.setState(2);
                        item.setStateName("租借中");
                    }else if(BXSCNShopOrderEnum.State.WaitRevert.index().equals(order.getState())
                            && BXSCNShopOrderEnum.PayState.DepositSuccess.index().equals(order.getPayState())){
                        item.setState(3);
                        item.setStateName("待归还");
                    }else {
                        if(BXSCNShopOrderEnum.PayState.Cancel.index().equals(order.getPayState())) {
                            item.setState(4);
                            item.setStateName("已撤销");
                        }else{
                            item.setState(5);
                            item.setStateName("已完成");
                        }
                    }

                    if(order.getStartDate() != null) {
                        item.setLeaseDateStr(DateFormatUtils.format(order.getStartDate(), "yyyy-MM-dd"));
                    }
                    if(order.getEndDate() != null){
                        item.setLeaseDateStr(item.getLeaseDateStr() + " / " + DateFormatUtils.format(order.getEndDate(),"MM-dd"));
                    }
                    item.setCreateDate(order.getCreateDate());
                    apiResp.getBody().getOrderItemList().add(item);
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/xcx/v1/member/bxscn_shop/order/info.data" }, method = "POST")
    public BXSCNMemberOrderInfoResponse orderInfo(HttpServletRequest request) {
        BXSCNMemberOrderInfoResponse apiResp = new BXSCNMemberOrderInfoResponse(ClientAPICodeConstants.NULL_DATA, "未找到订单信息");
        MemberOrderInfoRequest apiReq = WebUtils.getJsonRequest(request, MemberOrderInfoRequest.class);
        if (apiReq != null && apiReq.getBody().getTradeNo() != null) {
            LoginMember member = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
            Date currentDate = new Date();
            if(StringTools.isNotBlank(apiReq.getBody().getCreateDate())){
                try {
                    currentDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(),"yyy-MM-dd HH:mm:ss","yyy-MM-dd");
                } catch (ParseException e) {
                    log.error(e.getMessage(),e);
                }
            }
            BXSCNShopOrder bxscnShopOrder = BXSCNShopOrderService.self(currentDate).getByTradeNo(apiReq.getBody().getTradeNo());
            if (bxscnShopOrder != null && bxscnShopOrder.getMemberId().equals(member.getId())) {
                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);

                ClassTools.copy(apiResp.getBody(), bxscnShopOrder);
                apiResp.getBody().setCostMode(EBXSCNCostMode.Deposit.index());
                apiResp.getBody().setCostModeName(EBXSCNCostMode.Deposit.note());
                apiResp.getBody().setLeaseTypeName(bxscnShopOrder.getLeaseTypeName());
                apiResp.getBody().setLeaseAreaName(bxscnShopOrder.getPlaceAreaName());
                apiResp.getBody().setRevertTypeName(bxscnShopOrder.getRevertTypeName());
                apiResp.getBody().setRevertAreaName(bxscnShopOrder.getRevertAreaName());
                apiResp.getBody().setDepositMoneyStr(bxscnShopOrder.getDepositMoneyStr());
                apiResp.getBody().setDayMoneyStr(bxscnShopOrder.getDayMoneyStr());
                apiResp.getBody().setMoneyStr(bxscnShopOrder.getMoneyStr());
                apiResp.getBody().setPayMoneyStr(bxscnShopOrder.getPayMoneyStr());
                apiResp.getBody().setWalletMoneyStr(bxscnShopOrder.getWalletMoneyStr());
                apiResp.getBody().setDiscountMoneyStr(bxscnShopOrder.getDiscountMoneyStr());
                apiResp.getBody().setLogisticsMoneyStr(bxscnShopOrder.getLogisticsMoneyStr());
                apiResp.getBody().setDamageMoneyStr(bxscnShopOrder.getDamageMoneyStr());
                apiResp.getBody().setPayTypeName(bxscnShopOrder.getPayTypeName());

                if(bxscnShopOrder.getStartDate() != null) {
                    apiResp.getBody().setLeaseDateStr(DateFormatUtils.format(bxscnShopOrder.getStartDate(), "yyyy-MM-dd"));
                }
                if(bxscnShopOrder.getEndDate() != null){
                    apiResp.getBody().setLeaseDateStr(apiResp.getBody().getLeaseDateStr() + " / " + DateFormatUtils.format(bxscnShopOrder.getEndDate(),"MM-dd"));
                    apiResp.getBody().setExpectRevertDate(DateFormatUtils.format(bxscnShopOrder.getEndDate(), "yyyy-MM-dd"));
                }

                apiResp.getBody().setState(bxscnShopOrder.getState());
                apiResp.getBody().setStateName(bxscnShopOrder.getStateName());
                apiResp.getBody().setPayState(bxscnShopOrder.getPayState());
                apiResp.getBody().setPayStateName(bxscnShopOrder.getPayStateName());

                PortableEnergyBatteryType batteryType = PortableEnergyBatteryTypeService.self().getById(bxscnShopOrder.getBatteryType());
                if(batteryType != null){
                    String resDomain = PropertyTools.get().getString("resDomain");
                    apiResp.getBody().setBatteryImg(WebUtils.setHttpDomain(resDomain,batteryType.getThumbnailImg()));
                }

                PlacePhysicalStore leasePlace = PlacePhysicalStoreService.self().getById(bxscnShopOrder.getLeasePlaceId());
                if (leasePlace != null) {
                    apiResp.getBody().setLeaseRouteInfo(leasePlace.getRouteInfo());
                    apiResp.getBody().setLeasePlaceOpenTime(DateTools.changeHHmm(leasePlace.getOpenTime()));
                    apiResp.getBody().setLeasePlaceCloseTime(DateTools.changeHHmm(leasePlace.getCloseTime()));
                    apiResp.getBody().setLeasePlacePhone(leasePlace.getContactPhone());
                }
                if (bxscnShopOrder.getRevertPlaceId() != null) {
                    if (bxscnShopOrder.getLeasePlaceId().equals(bxscnShopOrder.getRevertPlaceId())) {
                        apiResp.getBody().setRevertRouteInfo(leasePlace.getRouteInfo());
                        apiResp.getBody().setRevertPlaceOpenTime(DateTools.changeHHmm(leasePlace.getOpenTime()));
                        apiResp.getBody().setRevertPlaceCloseTime(DateTools.changeHHmm(leasePlace.getCloseTime()));
                        apiResp.getBody().setRevertPlacePhone(leasePlace.getContactPhone());
                    } else {
                        PlacePhysicalStore revertPlace = PlacePhysicalStoreService.self().getById(bxscnShopOrder.getRevertPlaceId());
                        if (revertPlace != null) {
                            apiResp.getBody().setRevertRouteInfo(revertPlace.getRouteInfo());
                            apiResp.getBody().setRevertPlaceOpenTime(DateTools.changeHHmm(revertPlace.getOpenTime()));
                            apiResp.getBody().setRevertPlaceCloseTime(DateTools.changeHHmm(revertPlace.getCloseTime()));
                            apiResp.getBody().setRevertPlacePhone(revertPlace.getContactPhone());
                        }
                    }
                }

                if(BXSCNShopOrderEnum.State.WaitRevert.index().equals(bxscnShopOrder.getState())
                        || BXSCNShopOrderEnum.State.LeaseClose.index().equals(bxscnShopOrder.getState())){
                    apiResp.getBody().setTimeoutDay(0);
                    apiResp.getBody().setResidueMoneyStr("0");

                    Integer timeoutDay = DateTools.differenceDay(bxscnShopOrder.getEndDate(),new Date());
                    if(timeoutDay > 0) {
                        apiResp.getBody().setTimeoutDay(timeoutDay);
                        Integer payMoney = timeoutDay * bxscnShopOrder.getDayMoney();
                        Integer residueMoney = bxscnShopOrder.getDepositMoney() - payMoney;
                        if (residueMoney > 0) {
                            apiResp.getBody().setResidueMoneyStr(NumberTools.getMoneyStr(residueMoney));
                        }
                    }
                }
            }
        }
        return apiResp;
    }

}
